package com.shexianyu.simple;

import java.util.Stack;

/**
 * 20. 有效的括号
 */
public class IsValid {
    public boolean isValid(String s) {
        if (s.length() == 0) return false;
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            //若包含'( { ['字符就入栈
            if (s.charAt(i) == '(' || s.charAt(i) == '{' | s.charAt(i) == '[') {
                stack.push(s.charAt(i));
                //若栈为空，则第一个字符就是') ] }'之一
            } else if (stack.isEmpty()) {
                return false;
            } else {
                Character pop = stack.pop();
                if (s.charAt(i) == ')') {
                    if (pop != '(') return false;
                } else if (s.charAt(i) == '}') {
                    if (pop != '{') return false;
                } else if (s.charAt(i) == ']') {
                    if (pop != '[') return false;
                }
            }
        }
        return stack.isEmpty() ? true : false;
    }
}
